package com.dys.dao.impl;

import com.dys.dao.AccountDAO;
import com.dys.entity.Account;
import com.dys.util.DatabaseUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @className: com.dys.dao.impl.AccountDAOImpl
 * @description: AccountDAO的实现类：
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/09/13 下午9:13
 */
public class AccountDAOImpl implements AccountDAO {
    @Override
    public Account findAccountByCardNo(String cardNo) throws SQLException {
        // 1、获取连接
        Connection conn = DatabaseUtils.getConnection();
        // 2、编写SQL语句
        String sql = "select * from account where card_no=?";
        // 3、获取PreparedStatement，传入SQL
        PreparedStatement ps = conn.prepareStatement(sql);
        // 4、给占位符赋值
        ps.setString(1, cardNo);
        // 5、执行SQL，获取结果
        ResultSet rs = ps.executeQuery();
        // 6、处理返回结果
        Account account = null;
        while (rs.next()) {
            account = new Account();
            account.setId(rs.getInt("id"));
            account.setCardNo(rs.getString("card_no"));
            account.setName(rs.getString("name"));
            account.setPassword(rs.getString("password"));
            account.setMoney(rs.getBigDecimal("money"));
        }
        // 7、释放资源
        // DatabaseUtils.closeAll(conn, ps, rs);
        // 释放资源前置到service层
        DatabaseUtils.closeAll(null, ps, rs);
        // 8、返回结果
        return account;
    }

    @Override
    public int updateAccountByCardNo(Account account) throws SQLException {
        // 1、获取连接
        Connection conn = DatabaseUtils.getConnection();
        // 2、编写SQL语句
        String sql = "update account set money=? where card_no=?";
        // 3、获取PreparedStatement，传入SQL
        PreparedStatement ps = conn.prepareStatement(sql);
        // 4、给占位符赋值
        ps.setBigDecimal(1, account.getMoney());
        ps.setString(2, account.getCardNo());
        // 5、执行SQL，获取结果
        int count = ps.executeUpdate();
        // 6、释放资源
        // DatabaseUtils.closeAll(conn, ps);
        // 释放资源前置到service层
        DatabaseUtils.closeAll(null, ps);
        // 7、返回结果
        return count;
    }
}
